package com.hanoi.wiki.manager.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hanoi.wiki.dao.PlacesDAO;
import com.hanoi.wiki.dao.PlacesInQueuedDAO;
import com.hanoi.wiki.dao.RatesDAO;
import com.hanoi.wiki.exception.DataAccessException;
import com.hanoi.wiki.manager.RatesManager;
import com.hanoi.wiki.model.Places;
import com.hanoi.wiki.model.PlacesInQueued;
import com.hanoi.wiki.model.Rates;
import com.hanoi.wiki.model.json.RatesJson;

@Component
@Transactional
public class RatesManagerImpl extends BaseManagerImpl implements RatesManager{

	@Autowired
	private RatesDAO ratesDAO;
	
	@Autowired
	private PlacesDAO placesDAO;
	
	@Autowired
	private PlacesInQueuedDAO inQueuedDAO;
	
	public int save(RatesJson json) {
		try {
			Rates rates = new Rates(json);
			
			List<Places> places = new ArrayList<Places>();
			Places place;
			for(Integer i : json.getPlaces()) {
				place = placesDAO.get(i);
				if(place != null) {
					places.add(place);
				}
			}
			
			List<PlacesInQueued> inQueueds = new ArrayList<PlacesInQueued>();
			PlacesInQueued inQueued;
			for(Integer i : json.getPlacesInQueueds()) {
				inQueued = inQueuedDAO.get(i);
				if(inQueued != null) {
					inQueueds.add(inQueued);
				}
			}
			
			rates.setPlaces(places);
			rates.setPlacesInQueueds(inQueueds);
			
			return ratesDAO.saveRates(rates);
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return 0;
	}

	public void update(RatesJson json) {
		try {
			Rates rates = new Rates(json);
			
			List<Places> places = new ArrayList<Places>();
			Places place;
			for(Integer i : json.getPlaces()) {
				place = placesDAO.get(i);
				if(place != null) {
					places.add(place);
				}
			}
			
			List<PlacesInQueued> inQueueds = new ArrayList<PlacesInQueued>();
			PlacesInQueued inQueued;
			for(Integer i : json.getPlacesInQueueds()) {
				inQueued = inQueuedDAO.get(i);
				if(inQueued != null) {
					inQueueds.add(inQueued);
				}
			}
			
			rates.setPlaces(places);
			rates.setPlacesInQueueds(inQueueds);
			rates.setId(json.getId());
			
			ratesDAO.update(rates);
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}

	public RatesJson get(Integer id) {
		try {
			return new RatesJson(ratesDAO.get(id));
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return null;
	}

	public List<RatesJson> getList() {
		List<RatesJson> rateJsonList = new ArrayList<RatesJson>();
		List<Rates> ratesList = ratesDAO.getList();
		try {
			for(Rates rate : ratesList) {
				rateJsonList.add(new RatesJson(rate));
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
		return rateJsonList;
	}

	public void remove(Integer id) {
		try {
			if(ratesDAO.get(id) != null) {
				ratesDAO.remove(id);
			}
		} catch (DataAccessException e) {
			log.error("", e);
		}
	}

}
